package com.foogui.booteasyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.converters.date.DateDateConverter;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.foogui.booteasyexcel.converter.DateConverter;
import com.foogui.booteasyexcel.converter.StringConverter;
import com.foogui.booteasyexcel.handler.CustomSheetWriteHandler;
import com.foogui.booteasyexcel.listener.CustomerDailyImportListener;
import com.foogui.booteasyexcel.service.ReqCustomService;
import com.foogui.booteasyexcel.vo.ReqCustomerDailyImport;
import com.foogui.booteasyexcel.vo.RespCustomerDailyExport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/file")
@Slf4j
public class CustomerDailyImportController {
    private static final String CONTENT = "Content-Disposition";

    public static final String UTF_8 = "utf-8";

    @Autowired
    private ReqCustomService reqCustomService;

    /**
     * 下载模板
     *
     * @param response 响应
     * @throws IOException ioexception
     */

    @GetMapping(value = "/downloadTemplate/{systemId}")
    public void downloadTemplate(HttpServletResponse response, @PathVariable("systemId") String systemId) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding(UTF_8);
            // 防止中文乱码
            String fileName = URLEncoder.encode("业务字段导入模版", "UTF-8").replace("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcelFactory.write(response.getOutputStream(), ReqCustomerDailyImport.class)
                    .autoCloseStream(Boolean.FALSE)
                    // 根据查询数据中的信息创建下拉框的处理器
                    .registerWriteHandler(new CustomSheetWriteHandler(systemId,reqCustomService))
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .sheet("模板Sheet")
                    .doWrite(Collections.emptyList());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding(UTF_8);
            Map<String, String> map = new HashMap();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }

    @PostMapping("/import")
    public void importCustomerDaily(@RequestParam MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();


        List<ReqCustomerDailyImport> reqCustomerDailyImports = EasyExcelFactory.read(inputStream)
                // 这个转换是成全局的， 所有java为string,excel为string的都会用这个转换器。
                // .registerConverter(new DateConverter())
                // 注册监听器，可以在这里校验字段,这里注册监听器必须要new，或者让Spring接管Listener但是需要加@Scope("prototype")
                .registerReadListener(new CustomerDailyImportListener())
                .head(ReqCustomerDailyImport.class)
                // 设置sheet,默认读取第一个
                .sheet()
                // 设置标题所在行数
                .headRowNumber(1)
                .doReadSync();
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 生成数据
        List<RespCustomerDailyExport> data = Lists.newArrayList();

        for (int i = 0; i < 50; i++) {
            RespCustomerDailyExport respCustomerDailyExport = RespCustomerDailyExport.builder()
                    .misCode(String.valueOf(i))
                    .customerName("customerName" + i)
                    .monthlyQuota(new BigDecimal(String.valueOf(i)))
                    .accountReceivableQuota(new BigDecimal(String.valueOf(i)))
                    .dailyInterestRate(new BigDecimal(String.valueOf(i)))
                    .date(LocalDateTime.now()).build();
            data.add(respCustomerDailyExport);
        }
        // 设置相应的相关格式
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 防止中文乱码
        String fileName = URLEncoder.encode("业务字段导出", UTF_8).replace("\\+", "%20");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");


        EasyExcel.write(response.getOutputStream(), RespCustomerDailyExport.class)
                .sheet("sheet0")
                // 设置字段宽度为自动调整，不太精确
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .doWrite(data);
    }


    /**
     * 提供excel供下载
     *
     * @param response 响应
     * @throws IOException ioexception
     */
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response) throws IOException {
        //获取要下载的模板名称
        String fileName = URLEncoder.encode("业务字段导入模版.xlsx", "UTF-8").replaceAll("\\+", "%20");
        //设置要下载的文件的名称
        response.setHeader(CONTENT, "attachment;fileName=" + fileName);
        //通知客服文件的MIME类型
        response.setContentType("application/vnd.ms-template;charset=UTF-8");
        //获取文件的路径
        try {
            InputStream inputStream = null;

            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/model.xlsx");

            //读取excel模板
            XSSFWorkbook wb = new XSSFWorkbook(inputStream);
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error("下载模板出错：" + e);
        }
    }
}


